import React, { useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button } from 'react-vant'
import { useAppDispatch, useAppSelector } from '../../app/hooks';
import axios from 'axios';
import { setAvator } from '../../features/user';

const My: React.FC = () => {
  const navigate = useNavigate();
  const isLogin = useAppSelector(state => state.user.isLogin);
  const avator = useAppSelector(state => state.user.avator);
  const nickname = useAppSelector(state => state.user.nickname);
  const dispatch = useAppDispatch()
  const input = useRef<HTMLInputElement | null>(null)

  // 点击图片
  const chooseImage = () => {
    // 弹出文件选择器  => 只有input[type = file] 被点击事件触发的时候才会出现
    input.current?.click()
  }

  // 获取选中图片事件 
  const onchange = async (e: React.ChangeEvent<HTMLInputElement>) => {
  
    const file = (e.target.files as FileList)[0]
    const formData = new FormData();
    formData.append('file', file, file.name);
    const resp = await axios.post('/api/upload', formData)
    const { code, data, error } = resp.data;
    if(code === 200) {
      dispatch(setAvator(data.url))
    } else {
      console.log(error)
    }
  }


  return (
    <div>
      <input type="file" style={{ display: 'none' }} ref={input} onChange={(e) => onchange(e)} />
      {
        !isLogin ? <div className='not-login'>
          <Button type="primary" onClick={() => navigate(('/login'))}>还没有登录， 去登陆～</Button>
        </div> :
          <div className='user-info'>
            <img src={avator} alt="" onClick={() => chooseImage()} />
            <h3>{nickname}</h3>
          </div>
      }

    </div>
  )
}


export default My